// pages/index/index.js
Page({
  data: {
    currentDate: '',
    disciplineStats: {
      weeklySleep: 0,
      weeklyWake: 0,
      todaySleep: false,
      todayWake: false
    },
    healthStats: {
      weeklyMood: 0,
      positiveDays: 0,
      todayMood: false
    },
    // 操作频率限制
    operationCount: 0,
    lastOperationTime: 0
  },

  onLoad: function () {
    this.updateDate();
    this.loadStats();
    
    // 每分钟重置操作次数
    setInterval(() => {
      this.resetOperationCount();
    }, 60000);
  },

  onShow: function () {
    this.loadStats();
  },

  // 重置操作次数
  resetOperationCount: function () {
    this.setData({
      operationCount: 0
    });
  },

  // 检查操作频率限制
  checkOperationLimit: function () {
    const now = Date.now();
    const timeDiff = now - this.data.lastOperationTime;
    
    // 如果距离上次操作不到1分钟，检查操作次数
    if (timeDiff < 60000) {
      if (this.data.operationCount >= 6) {
        wx.showToast({
          title: '操作过于频繁，请稍后再试',
          icon: 'none',
          duration: 2000
        });
        return false;
      }
    } else {
      // 超过1分钟，重置操作次数
      this.setData({
        operationCount: 0
      });
    }
    
    // 更新操作记录
    this.setData({
      operationCount: this.data.operationCount + 1,
      lastOperationTime: now
    });
    
    return true;
  },

  // 格式化日期为中文
  formatDate: function (date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
    const weekday = weekdays[date.getDay()];
    
    return `${year}年${month}月${day}日 星期${weekday}`;
  },

  // 更新日期
  updateDate: function () {
    const now = new Date();
    const currentDate = this.formatDate(now);
    
    this.setData({
      currentDate: currentDate
    });
  },

  // 加载统计数据
  loadStats: function () {
    this.loadDisciplineStats();
    this.loadHealthStats();
  },

  // 加载自律系统统计
  loadDisciplineStats: function () {
    const records = wx.getStorageSync('sleepRecords') || [];
    const now = new Date();
    const today = this.formatDate(now);
    const weekStart = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
    
    // 本周统计
    const weeklyRecords = records.filter(record => {
      const recordDate = new Date(record.date);
      return recordDate >= weekStart;
    });
    
    const weeklySleep = weeklyRecords.filter(record => 
      record.type === 'sleep' && record.isOnTime
    ).length;
    
    const weeklyWake = weeklyRecords.filter(record => 
      record.type === 'wake' && record.isOnTime
    ).length;
    
    // 今日统计
    const todayRecords = records.filter(record => record.date === today);
    const todaySleep = todayRecords.some(record => record.type === 'sleep');
    const todayWake = todayRecords.some(record => record.type === 'wake');
    
    this.setData({
      'disciplineStats.weeklySleep': weeklySleep,
      'disciplineStats.weeklyWake': weeklyWake,
      'disciplineStats.todaySleep': todaySleep,
      'disciplineStats.todayWake': todayWake
    });
  },

  // 加载健康系统统计
  loadHealthStats: function () {
    const records = wx.getStorageSync('moodRecords') || [];
    const now = new Date();
    const today = this.formatDate(now);
    const weekStart = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
    
    // 本周统计
    const weeklyRecords = records.filter(record => {
      const recordDate = new Date(record.date);
      return recordDate >= weekStart;
    });
    
    if (weeklyRecords.length > 0) {
      const totalMood = weeklyRecords.reduce((sum, record) => sum + record.level, 0);
      const weeklyMood = (totalMood / weeklyRecords.length).toFixed(1);
      const positiveDays = weeklyRecords.filter(record => record.level >= 4).length;
      
      this.setData({
        'healthStats.weeklyMood': parseFloat(weeklyMood),
        'healthStats.positiveDays': positiveDays
      });
    }
    
    // 今日统计
    const todayRecord = records.find(record => record.date === today);
    this.setData({
      'healthStats.todayMood': !!todayRecord
    });
  },

  // 导航到自律系统
  navigateToDiscipline: function () {
    wx.switchTab({
      url: '/pages/discipline/index'
    });
  },

  // 导航到健康系统
  navigateToHealth: function () {
    wx.switchTab({
      url: '/pages/health/index'
    });
  },

  // 快速早睡打卡
  quickSleepCheck: function () {
    if (!this.checkOperationLimit()) {
      return;
    }

    if (this.data.disciplineStats.todaySleep) {
      wx.showToast({
        title: '今天已经早睡打卡了',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    wx.switchTab({
      url: '/pages/discipline/index'
    });
  },

  // 快速早起打卡
  quickWakeCheck: function () {
    if (!this.checkOperationLimit()) {
      return;
    }

    if (this.data.disciplineStats.todayWake) {
      wx.showToast({
        title: '今天已经早起打卡了',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    wx.switchTab({
      url: '/pages/discipline/index'
    });
  },

  // 快速记录心情
  quickMoodRecord: function () {
    if (!this.checkOperationLimit()) {
      return;
    }

    if (this.data.healthStats.todayMood) {
      wx.showToast({
        title: '今天已经记录心情了',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    wx.switchTab({
      url: '/pages/health/index'
    });
  }
});
